package com.satan.juc.demo12;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerExample {
    private final Queue<Integer> queue = new LinkedList<>();
    private final int MAX_CAPACITY = 10;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    // 生产者方法
    public void produce() throws InterruptedException {
        int value = 0;
        while (true) {
            lock.lock();
            try {
                // 等待队列不满
                while (queue.size() == MAX_CAPACITY) {
                    notFull.await();
                }
                queue.add(value);
                System.out.println("生产者生产: " + value);
                value++;
                // 通知消费者队列中有数据了
                notEmpty.signal();
            } finally {
                lock.unlock();
            }
            Thread.sleep(1000); // 模拟生产需要的时间
        }
    }

    // 消费者方法
    public void consume() throws InterruptedException {
        while (true) {
            lock.lock();
            try {
                // 等待队列不空
                while (queue.isEmpty()) {
                    notEmpty.await();
                }
                int value = queue.poll();
                System.out.println("消费者消费: " + value);
                // 通知生产者队列有空位了
                notFull.signal();
            } finally {
                lock.unlock();
            }
            Thread.sleep(1000); // 模拟消费需要的时间
        }
    }

    public static void main(String[] args) {
        ProducerConsumerExample example = new ProducerConsumerExample();
        // 创建生产者和消费者线程
        Thread producerThread = new Thread(() -> {
            try {
                example.produce();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumerThread = new Thread(() -> {
            try {
                example.consume();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 启动线程
        producerThread.start();
        consumerThread.start();
    }
}
